import React, { useRef } from 'react';
import { InputNumber, Select, message } from 'antd';

import CustomForm from 'src/components/CustomForm';
import services from 'src/services/api';

export default function WarningSetting(props) {
  const form = useRef(null);
  const { appLists = [], productList = [] } = props;

  function handleSubmit() {
    form.current.validateFields((err, values) => {
      if (!err) {
        try {
          const params = {
            dashboard_config: {
              ...values,
            },
          };

          services.riskDashboard.setting(params).then((res) => {
            if (res.code === 0) {
              message.success(res.msg);
              props.reSetFrequency && props.reSetFrequency(values.refresh_frequency);
            } else {
              message.error(res.msg);
            }
          });
        } catch (err) {
          message.warning(err);
          return;
        }
      }
    });
  }
  const formItems = [
    {
      label: {
        label: '展示渠道',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'app_id',
      options: {
        initialValue: props.app_id,
        rules: [{ required: true, message: '请选择展示渠道' }],
      },
      component: (
        <Select style={{ width: '200px' }} placeholder='请选择渠道'>
          {appLists.map((it) => {
            return (
              <Select.Option value={it.app_id} key={it.app_id}>
                {it.app_name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '展示产品',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'product_id',
      options: {
        initialValue: props.product_id === -1 ? '' : props.product_id,
      },
      component: (
        <Select style={{ width: '200px' }} placeholder='请选择产品' allowClear>
          {productList.map((it) => {
            return (
              <Select.Option value={it.product_id} key={it.product_id}>
                {it.product_name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '刷新频率',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'refresh_frequency',
      options: {
        initialValue: props.refresh_frequency,
        rules: [{ required: true, message: '请选择' }],
      },
      component: <InputNumber step={1} min={5} max={99} />,
      after: '秒',
    },
  ].filter(Boolean);
  return (
    <div>
      <CustomForm
        colNum={1}
        createForm={(ref) => (form.current = ref)}
        formItems={formItems}
        onHandleSubmit={() => handleSubmit()}
        className='warning-setting'
        confirmText='确定'
        closeModal={() => props.closeModal()}
      />
    </div>
  );
}
